package example;

import com.aliyun.fc.runtime.*;
import example.core.controller.ControllerMateUtil;
import example.core.router.Router;
import example.core.springcontext.ApplicationContextUtil;
import example.core.proerties.FcProerties;
import example.core.proerties.YmlUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 阿里函数计算启动类
 * @author 王振宇
 */
public class App implements HttpRequestHandler, FunctionInitializer {

    public static void main(String[] args) {
        App app = new App();
        app.initialize(new FcContext());
    }

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context)
            throws IOException {
        // 从Spring框架中获取路由实现类 进行路由匹配操作
        Router router = ApplicationContextUtil.applicationContext.getBean(Router.class);
        router.urlRouter(request, response, context);
    }

    /**
     * 函数执行之前 初始化操作
     * @param context 会话
     */
    @Override
    public void initialize(Context context) {
        // 读取框架配置文件
        FcProerties fcProerties = YmlUtil.getProerties();
        String[] basePackages = fcProerties.getSpringProerties().getScanBasePackages().split(",");
        ApplicationContextUtil.initSpring(context, basePackages);
        ControllerMateUtil.initCashMap();
        context.getLogger().info("init ok");
    }
}
